<template>
  <div class="search-container">
    <!-- 设置默认第一项高亮 :highlight-first-item="true" -->
    <!-- 隐藏加载中动画 :hide-loading="true" -->
    <el-autocomplete ref="searchInputRef" class="search-input" v-model="keyword" :fetch-suggestions="querySearchAsync"
      placeholder="搜索游戏" @select="handleSelect" clearable @focus="loadAll">
      <!-- 搜索结果模板 -->
      <template #default="{ item, index }">
        <!-- 搜索结果标题 -->
        <template v-if="item.type === 'header'">
          <div class="search-result-header">搜索结果</div>
        </template>

        <!-- 普通游戏项 -->
        <template v-else-if="item.type !== 'empty' && item.type !== 'more'">
          <div class="search-item" @click="navigateToGameDetail(item)">
            <div class="search-item-content">
              <img :src="item.iconUrl" alt="" width="40" height="40" />
              <div class="search-item-info">
                <div class="search-item-name">{{ item.title }}</div>
                <div
                  :class="['search-item-tag', item.cornerMarkers && item.cornerMarkers.length && item.cornerMarkers[0] == 2 ? 'free' : '']">
                  免费玩
                </div>
              </div>
            </div>
            <el-button type="primary" class="play-btn" v-if="item.session && item.session.status == 'online'"
              style="color: #FFE500;" @click.stop="gameDetailHandlePlayGame(item.id)">
              继续游戏
            </el-button>
            <el-button type="primary" class="play-btn"  @click.stop="gameDetailHandlePlayGame(item.id)" v-else>
              <el-icon>
                <img src="@/assets/svgs/thunder.svg" alt="秒玩图标" />
              </el-icon>
              秒玩
            </el-button>

          </div>
        </template>

        <!-- 无数据提示 -->
        <template v-else-if="item.type === 'empty'">
          <div class="empty-item">
            找不到喜欢的游戏？
            <el-button type="primary" class="suggest-btn" @click="suggestGame">
              告诉我们 <el-icon>
                <Right />
              </el-icon>
            </el-button>
          </div>
        </template>

        <!-- 查看更多按钮 -->
        <template v-else-if="item.type === 'more'">
          <div class="more-item">
            <el-button type="primary" class="more-btn" @click="viewMoreGames" plain>
              查看更多
            </el-button>
          </div>
        </template>
      </template>
    </el-autocomplete>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { gameApi } from '@/api/game.js'
import { useRouter } from 'vue-router'
import { Right } from '@element-plus/icons-vue'
import { defineEmits } from 'vue';
const emit = defineEmits(['call-parent-method']);
import { useLoginCheck, handlePlayGame } from "@/utils/auth.js";

// 游戏ID
const gameId = ref('')
// 是否正在播放游戏
const isPlaying = ref(false)
// 搜索相关变量
const keyword = ref('')
const links = ref([])
const isSearching = ref(false)
const router = useRouter()
const searchInputRef = ref(null) // 添加模板引用

// 秒玩游戏处理函数
const gameDetailHandlePlayGame = (id) => {
  gameId.value = id;
  isPlaying.value = true;
  // 传入目标类型:1=云游戏;2=云电脑
  handlePlayGame(id, "1", handlePlayGameCallback, 1);
}
// 使用全局handlePlayGame方法
const handlePlayGameCallback = (status, data) => {
  switch (status) {
    case "cancel": //取消
      isPlaying.value = false;
      break;
    case "confirm": //确认
      isPlaying.value = false;
      // 传入目标类型:1=云游戏;2=云电脑
      handlePlayGame(gameId.value, "1", handlePlayGameCallback, 0);
      break;
  }
};


// 加载搜索数据
const loadAll = () => {
  // 获取推荐游戏作为初始默认数据
  let params = {
    "page": 1,
    "rows": 5
  }
  gameApi.getHotRecommendGames(params).then(res => {
    links.value = res.games
  })
}

// 搜索异步查询函数
const querySearchAsync = (queryString, cb) => {
  isSearching.value = !!queryString

  if (queryString) {
    // 有搜索关键词时，调用搜索接口
    let params = {
      "page": 1,
      "rows": 5,
      "keyword": queryString
    }
    gameApi.getSearchGames(params).then(res => {
      let results = []

      if (res.games && res.games.length > 0) {
        // 查询有数据的情况
        results = [...res.games]
        // 添加搜索结果标题（放在第一个位置）
        results.unshift({ type: 'header' })
        // 当搜索结果超过5个时才显示查看更多按钮
        if (res.games.length > 5) {
          results.push({ type: 'more' })
        }
      } else {
        // 查询无数据的情况
        results = [{ type: 'empty' }]
      }

      cb(results)
    }).catch(() => {
      // 出错时返回无数据提示
      cb([{ type: 'empty' }])
    })
  } else {
    // 无搜索关键词时，显示初始默认数据
    const results = [...links.value]
    cb(results)
  }
}

// 选择搜索结果处理
const handleSelect = (item) => {
  // 忽略特殊类型的项
  if (item.type) return
  console.log('选择了游戏:', item)
  // 这里可以添加游戏选择后的逻辑
}

// 查看更多游戏
const viewMoreGames = () => {
  console.log('查看更多游戏，关键词:', keyword.value)
  // 这里可以实现查看更多的逻辑，比如跳转到搜索结果页
  router.push({ name: 'SearchResults', query: { keyword: keyword.value } })
}

// 游戏推荐反馈
const suggestGame = () => {
  console.log('用户点击了告诉我们按钮')
  // 这里可以实现反馈逻辑，比如打开反馈弹窗
  emit('call-parent-method');
}
// 跳转到游戏详情页
const navigateToGameDetail = (item) => {
  // 清空搜索关键词
  keyword.value = ''
  try {
    // let tempElement = document.getElementById('temp-focus-element')
    // if (!tempElement) {
    //   tempElement = document.createElement('input')
    //   tempElement.id = 'temp-focus-element'
    //   tempElement.style.position = 'absolute'
    //   tempElement.style.opacity = '0'
    //   tempElement.style.pointerEvents = 'none'
    //   document.body.appendChild(tempElement)
    // }
    // tempElement.focus()

    setTimeout(() => {
      const inputElement = document.querySelector('.search-input input')
      if (inputElement) {
        inputElement.classList.remove('el-input__inner--focus')
        inputElement.blur()
      }
      if (searchInputRef.value && searchInputRef.value.close) {
        searchInputRef.value.close()
      }
    }, 0)
  } catch (e) {
    console.log('清除焦点失败', e)
  }

  // 执行路由跳转
  router.push({
    path: `/cloudGaming/detail/${item.id}`,
  })
}


// 组件挂载时加载初始数据
onMounted(() => {
  loadAll()
})
</script>

<style lang="scss" scoped>
.search-container {
  width: 324px;
  position: relative;

  :deep(.el-input__wrapper) {
    box-shadow: none;
    border: 1px solid #47494A;
    background-color: #2E3031;
  }

  :deep(.search-input) {
    width: 100%;
    height: 32px;
    box-shadow: none !important;

    .el-input__icon {
      color: #888;
    }
  }
}
</style>

<style lang="scss">
// 搜索结果弹出框样式需要全局样式才能生效
.el-autocomplete__popper {
  width: 324px;
  background: #141414 !important;
  border: 1px solid #46484A !important;
  box-sizing: border-box;
  overflow: hidden;

  .el-autocomplete-suggestion__wrap {
    max-height: 340px !important;
    padding: 0 !important;
  }

  .el-popper__arrow {
    display: none !important;
  }

  .el-autocomplete-suggestion li {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    height: auto !important;
    min-height: 60px !important;

    // 普通游戏项高度
    // &:not(.empty-item-container):not(.more-item-container) {
    //   height: 60px;
    // }

    // 搜索结果标题项
    &:first-child .search-result-header {
      padding: 0 10px;
      font-size: 16px;
      color: #888;
      line-height: 60px;
    }

    // 无数据提示项高度
    &.empty-item-container {
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    // 查看更多按钮项高度
    &.more-item-container {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-top: 1px solid #232527;
    }

    .search-item {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100%;
      gap: 10px;
      padding: 0 10px;

      &:hover {
        background-color: #232527 !important;
      }

      .search-item-content {
        display: flex;
        align-items: center;
        flex: 1;

        img {
          width: 48px;
          height: 48px;
          display: block;
          border-radius: 4px;
        }

        .search-item-info {
          margin-left: 8px;

          .search-item-name {
            width: 140px;
            line-height: 24px;
            color: #fff;
            font-size: 14px;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .search-item-tag {
            color: #888;
            font-size: 12px;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;

            &.free {
              color: #ffe500;
            }
          }

        }
      }

      .play-btn {
        width: 66px;
        height: 28px;
        font-size: 12px;
        background-color: #232527;
        border-color: #232527;
        color: #fff;
        border-radius: 4px;
      }
    }

    // 无数据提示样式
    .empty-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      width: 100%;
      height: 100%;
      padding: 20px 0;
      color: #888;
      font-size: 14px;

      &:hover+li {
        background-color: transparent !important;

      }

      .suggest-btn {
        margin-top: 10px;
        height: 32px;
        padding: 0 20px;
        background-color: #ffe500;
        border-color: #ffe500;
        color: #222;
        font-size: 14px;
        border-radius: 4px;
      }
    }

    // 查看更多按钮样式
    .more-item {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 20px 0;

      .more-btn {
        height: 32px;
        padding: 0 20px;
        background-color: transparent;
        border-color: #46484A;
        color: #888;
        font-size: 14px;
        border-radius: 4px;
      }
    }
  }

  // 悬停和高亮样式
  .el-autocomplete-suggestion li:not(.empty-item-container):not(.more-item-container).highlighted,
  .el-autocomplete-suggestion li:not(.empty-item-container):not(.more-item-container):hover {
    background-color: transparent !important;

    .play-btn {
      background: #4f5255;
    }
  }

  // 无数据项不响应悬停
  .el-autocomplete-suggestion li.empty-item-container:hover,
  .el-autocomplete-suggestion li.more-item-container:hover {
    background-color: #141414 !important;
  }
}
</style>